#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#include <DHT.h>
#include <FS.h>

DHT sensor(D1, DHT11);
ESP8266WebServer server;

void handle_root()
{
  File file = SPIFFS.open("/index.html", "r");
  server.streamFile(file, "text/html");
}

void handle_sensor()
{
  const size_t capacity = JSON_OBJECT_SIZE(2);
  DynamicJsonDocument doc(capacity);

  doc["temp"] = sensor.readTemperature();
  doc["humi"] = sensor.readHumidity();

  String msg;
  serializeJson(doc, msg);
  server.send(200, "application/json", msg.c_str());
}

void setup(void)
{
  Serial.begin(115200);
  sensor.begin();
  SPIFFS.begin();
  WiFi.mode(WIFI_STA);
  WiFi.begin("LIUYU", "12345678");
  while (!WiFi.isConnected())
  {
    delay(500);
  }
  Serial.println(WiFi.localIP());

  server.on("/", handle_root);
  server.on("/sensor", handle_sensor);
  server.begin();
}

void loop(void)
{
  server.handleClient();
}
